package com.Nahida.NaHome.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.Nahida.NaHome.R;
import com.Nahida.NaHome.activity.base.BaseActivity;
import com.Nahida.NaHome.activity.settings.SettingMainActivity;
import com.Nahida.NaHome.adapter.HomeAdapter;
import com.Nahida.NaHome.model.HomeButton;
import com.Nahida.NaHome.service.FloatService;
import com.Nahida.NaHome.util.MsgUtil;
import com.Nahida.NaHome.util.SharedPreferencesUtil;
import com.Nahida.NaHome.view.BatteryView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;


/*
桌面主页
 */
public class HomeActivity extends BaseActivity {

    TextView clock,battery_percent;
    BatteryView batteryView;
    ImageView icon_wifi, icon_bluetooth;

    BroadcastReceiver broadcastReceiver;
    WifiManager wifiManager;
    BluetoothAdapter bluetoothAdapter;
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm yyyy/MM/dd E", Locale.CHINA);
    Timer connectionTimer;

    HomeButton scanActivity;

    boolean flag_gotojxw = false;
    int timeClick = 0;
    int scanKey;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        if(!checkFloatPermission()) requestFloatPermission();  //检查权限

        scanKey = SharedPreferencesUtil.getInt("scankey", 286);

        int first_use = SharedPreferencesUtil.getInt("first_use",0);
        if(first_use < 1){
            Intent intent = new Intent(this, ShowTextActivity.class);
            intent.putExtra("title","使用教程");
            intent.putExtra("content", getString(R.string.introduction));
            intent.putExtra("disable_back", true);
            startActivity(intent);
            SharedPreferencesUtil.putInt("first_use",first_use+1);
        }

        clock = findViewById(R.id.clock);
        battery_percent = findViewById(R.id.battery_percent);
        batteryView = findViewById(R.id.battery);
        icon_wifi = findViewById(R.id.wifi);
        icon_bluetooth = findViewById(R.id.bluetooth);

        clock.setText(dateFormat.format(new Date()));
        clock.setOnClickListener(v -> timeClick++);

        connectionTimer = new Timer();
        wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        connectionTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(()->{
                    if(wifiManager.isWifiEnabled()){
                        icon_wifi.setVisibility(View.VISIBLE);
                        int wifi_strength = wifiManager.getConnectionInfo().getRssi();
                        int icon;
                        // 使用系统API获取WIFI信号强度
                        // 5个等级
                        int level = WifiManager.calculateSignalLevel(wifi_strength, 5);
                        switch (level) {
                            case 0:
                                icon = R.mipmap.wifi0;
                                break;
                            case 1:
                                icon = R.mipmap.wifi1;
                                break;
                            case 2:
                                icon = R.mipmap.wifi2;
                                break;
                            case 3:
                                icon = R.mipmap.wifi3;
                                break;
                            case 4:
                                icon = R.mipmap.wifi4;
                                break;
                            default:
                                icon = R.mipmap.wifi0;
                                break;
                        }
                        icon_wifi.setImageResource(icon);
                    }
                    else icon_wifi.setVisibility(View.GONE);

                    if(bluetoothAdapter.isEnabled()){
                        icon_bluetooth.setVisibility(View.VISIBLE);
                    }
                    else icon_bluetooth.setVisibility(View.GONE);
                });
            }
        }, 100, 2000);



        //主页按钮

        scanActivity = new HomeButton(R.mipmap.saomiaofanyi,"com.jxw.launcher","com.jxw.scanpen.a19.ui.ScanPenActivity");

        //按钮列表，可编辑
        ArrayList<HomeButton> list = new ArrayList<HomeButton>(){{
            add(scanActivity);

            //九学王的命名风格太逆天了，全是拼音
            add(new HomeButton(R.mipmap.wenbenzhaichao,"com.jxw.wbzc",""));
            add(new HomeButton(R.mipmap.zjm_beidanci,"com.jxw.xwbdc",""));
            add(new HomeButton(R.mipmap.yuyinfanyi,"com.jxw.zhongyinghuyi.online","com.jxw.zhongyinghuyi.online.MainActivity"));
            add(new HomeButton(R.mipmap.shengciben,"com.jxw.launcher","com.jxw.launcher.SPNewWordBookActivity"));
            //add(new HomeButton(R.mipmap.zhinengdayi,"",""));
            //add(new HomeButton(R.mipmap.tongbushipin,"",""));
            //add(new HomeButton(R.mipmap.xuebazaiting,"",""));
            add(new HomeButton(R.mipmap.yinyue,"com.jxw.music","com.jxw.music.MainActivity"));
            //add(new HomeButton(R.mipmap.jingpinyingyong,"",""));

            add(new HomeButton(R.mipmap.shezhi,"com.jxw.launcher","com.jxw.launcher.SPSZActivity"));
        }};

        //设置adapter来显示
        HomeAdapter adapter = new HomeAdapter(this, list);
        
        adapter.setOnClickListener(position -> {
            if(position == 0){
                startScanBackService();
            }
            flag_gotojxw = true;
        });

        adapter.setOnLongClickListener(position -> {
            // 直接长按打开应用列表
            timeClick = 3;
            if(timeClick==3){
                timeClick = 0;
                if(position == 0){
                    MsgUtil.showMsg("双击悬浮球快速返回", this);
                    startActivity(new Intent(this, RealAppsActivity.class));
                }
                if(position == list.size()-1){
                    startActivity(new Intent(this, SettingMainActivity.class));
                }
            }
        });

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        recyclerView.setAdapter(adapter);


        //以下为接收系统广播（监听时钟和电量变化）
        broadcastReceiver = new BroadcastReceiver() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action){
                    case Intent.ACTION_TIME_TICK:
                        clock.setText(dateFormat.format(new Date()));
                        break;
                    case Intent.ACTION_BATTERY_CHANGED:
                        int level = intent.getIntExtra("level", 0);
                        int scale = intent.getIntExtra("scale", 0);
                        int plugged = intent.getIntExtra("plugged", 0);
                        int percent = level * 100 / scale;
                        battery_percent.setText(percent + "%");
                        batteryView.setPower(percent);
                        batteryView.setCharging(plugged!=0);
                        break;
                }
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);

        registerReceiver(broadcastReceiver, filter);

    }

    @Override
    protected void onPause() {
        if(!flag_gotojxw) startAppHomeService();
        else flag_gotojxw = false;
        super.onPause();
        //MsgUtil.showMsg("NaHome进入后台", this);
    }

    @Override
    protected void onResume() {
        flag_gotojxw = false;
        stopFloatService();
        super.onResume();
        //MsgUtil.showMsg("NaHome进入前台", this);
    }

    @Override
    public void onBackPressed() {}

    @Override
    protected void onDestroy() {
        unregisterReceiver(broadcastReceiver);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == scanKey && event.getAction() == KeyEvent.ACTION_DOWN){
            if(scanActivity.packageName!=null && !scanActivity.packageName.isEmpty()) {
                Intent intent = new Intent();
                intent.setClassName(scanActivity.packageName, scanActivity.activityName);  //识别扫描键并跳转
                startActivity(intent);
                startScanBackService();
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    private boolean checkFloatPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true;
        else return Settings.canDrawOverlays(this);
    }

    private void requestFloatPermission(){
        if (Build.VERSION.SDK_INT >= 23){
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
            int code = 0;
            startActivityForResult(intent, code);
        }
    }

    private void startScanBackService(){
        stopFloatService();
        flag_gotojxw = true;
        Intent service = new Intent(this, FloatService.class);
        service.putExtra("type","scan");
        startService(service);
    }

    private void startAppHomeService(){
        stopFloatService();
        flag_gotojxw = false;
        startService(new Intent(this, FloatService.class));
    }

    private void stopFloatService(){
        stopService(new Intent(this,FloatService.class));
    }

}
